package concurrent;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class MapCountExample {
    private static Map<Integer, Integer> map = new HashMap<>();

    //有200个用户同时访问
    private static int threadNum = 200;
    //系统短时间内接收到5000个请求
    private static int clientTotal = 5000;

    public static void main(String[] args) {
        //线程池
        ExecutorService exec = Executors.newCachedThreadPool();
        //信号量
        final Semaphore semaphore = new Semaphore(threadNum);

        //模拟客户端发送的5000个请求。同一时间内允许200个请求同时执行
        for(int index = 0; index < clientTotal; index++){
            final int threadNum = index;
            exec.execute(() -> {
                try{
                    semaphore.acquire();
                    func(threadNum);
                    semaphore.release();

                }catch (Exception e){
                    e.printStackTrace();
                }
            });
        }

        exec.shutdown();
        System.out.println("count: " + map.size());
    }

    private static void func(int threadTotal) {
        map.put(threadTotal, threadTotal);
    }
}
